<template>
  <div class="pages cika">
    <div class="pageLevel" v-if="!sub">
      <div class="operationBox tableSearch">
        <el-button type="primary" size="mini" v-if="setRole('新增次卡')" @click="routerPush()">新增次卡</el-button>
      </div>
      <!-- 搜索框 -->
      <div class="tableSearch">
        <el-form label-width="100px" class="demo-ruleForm">
          <el-form-item label="" label-width="15px">
            <el-input class="input" v-model="selectdata.keyword" size="small" placeholder="请输入编号或卡名搜索"></el-input>
            <el-input class="input" v-model="selectdata.frequency" size="small" placeholder="次卡次数"></el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="50px">
            <el-select v-model="selectdata.status" placeholder="请选择状态" size="small" style="width:150px;">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
            <el-form-item label="是否提成" label-width="80px" v-if="!(soUrce !=5&&isShop==0)">
            <el-select v-model="selectdata.isCommission" size="small" style="width:150px;">
              <el-option v-for="item in commissionOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" label-width="15px">
            <el-button type="primary" size="mini" @click="searchSelect" class="Button">查询</el-button>

            <el-button type="primary" size="mini" @click="onSetCommission" class="Button" v-if="setRole('设置次卡提成') && !(soUrce !=5&&isShop==0)">设置次卡提成</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table :data="tableData" stripe @selection-change="handleSelectionChange" style="width: 100%">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="code" label="编号" align="center">
          </el-table-column>
          <el-table-column prop="name" label="卡名" align="center">
          </el-table-column>
          <el-table-column prop="servicesName" align="center" label="服务">
          </el-table-column>
          <el-table-column prop="times" align="center" label="次数">
          </el-table-column>
          <el-table-column prop="originPrice" align="center" label="价格">
          </el-table-column>
          <el-table-column align="center" label="销售数量">
            <template slot-scope="scope">
              <el-button type="text" size="small" class="addDetail" @click="routerPushNumber(scope.row.id)">{{scope.row.saleCount}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="state" align="center" :formatter="states" label="状态"></el-table-column>
          <el-table-column prop="royalty" align="center" label="是否提成" v-if="!(soUrce !=5&&isShop==0)">
            <template slot-scope="scope">
              <span v-if="scope.row.royalty == 0">否</span>
              <span v-if="scope.row.royalty == 1">是</span>
            </template>
          </el-table-column>
          <el-table-column prop="deductAmount" align="center" label="提成比例/金额" v-if="!(soUrce !=5&&isShop==0)">
            <template slot-scope="scope">
              <span v-if="scope.row.royalty == 1">
                 {{scope.row.deductAmount}}
                 <span v-if="scope.row.deductType == 0">%</span>
                 <span v-if="scope.row.deductType == 1">元</span>
              </span>
              <span v-if="scope.row.royalty == 0">
                --
              </span>

            </template>
          </el-table-column>
          <el-table-column prop="createTime" :formatter="timestamps" align="center" label="创建时间">
          </el-table-column>
          <el-table-column prop="name" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <!-- <el-button type="text" v-if="storeif" size="small" @click="handleViewStore(scope.row.id)">查看分配门店</el-button> -->
              <el-button size="small" v-if="setRole('编辑')" @click="routerPushdetail('1',scope.row.id)" type="text" class="addDetail">编辑</el-button>
              <el-button size="small" v-if="scope.row.state=='1'&&setRole('删除')" @click="deletes(scope.row.id)" type="text" class="delete">删除</el-button>
              <el-button size="small" @click="routerPushdetails('2',scope.row.id)" type="text" class="addDetail">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码 -->
        <div class="pageblock">
          <el-button size="small" type="primary" class="topage" @click="toPage">确定</el-button>
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20,30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="totalItems">
          </el-pagination>
        </div>
        <!-- 分配门店对话框 -->
        <el-dialog class="discount-css addshopname" title="选择门店" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="dialogVisible_store" width="50%">
          <div class="prices">
            <el-form>
              <el-form-item>
                <el-input size="small" class="inp-sr" v-model="keyword_s" placeholder="请输入门店名称或编号"></el-input>
                <el-button size="small" type="primary" @click="handleFenpei_do_search">搜索</el-button>
              </el-form-item>
            </el-form>
            <el-table max-height="250" :data="store_fenpei" @selection-change="changeFun_addStore">
              <el-table-column type="selection" width="55" class="selection" property='shopId' label="选择"></el-table-column>
              <el-table-column property="shopName" align="center" label="门店名称"> </el-table-column>
              <el-table-column property="shopCode" align="center" label="编号"> </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer dialog-footer-top" style="display: inline-block; margin-top:20px;margin-left: 38%;">
              <el-button class="dialog-footer-button" size="small" type="primary" @click="handleFenpei_s()">立即分配</el-button>
              <el-button class="dialog-footer-button" size="small" @click="dialogVisible_store = false">取 消</el-button>
            </span>
          </div>
        </el-dialog>
        <!-- 查看分配门店对话框 -->
        <el-dialog class="discount-css" title="已分配门店-活动名称" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="dialogVisible_check_store" width="50%">
          <div class="prices">
            <el-form>
              <el-form-item class="gys">
                <el-input size="small" class="inp-sr" v-model="keyword_store" placeholder="请输入门店名称或编号搜索"></el-input>
                <el-button size="small" type="primary" @click="handleFenpei_search">搜索</el-button>
                <!-- <el-button size="small" class="batch" type="primary" @click="handleCancelFenpei_more">批量取消分配</el-button> -->
              </el-form-item>
            </el-form>
            <el-table :data="tableDataStore" border @selection-change="change_store">
              <!-- <el-table-column type="selection" width="50"></el-table-column> -->
              <el-table-column prop="shopName" align="center" label="门店名称"> </el-table-column>
              <el-table-column prop="shopCode" align="center" label="编号"> </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="handleCancelFenpei_more(scope.row.shopId)">取消分配</el-button>
                </template>
              </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer dialog-footer-top" style="display: inline-block; margin-top:20px;margin-left: 42%;">
              <el-button class="dialog-footer-button" size="small" @click="dialogVisible_check_store = false">返回</el-button>
            </span>
          </div>
        </el-dialog>
      </div>
    </div>
    <div class="pageLevel" v-else>
      <router-view></router-view>
    </div>
    <el-dialog title="设置次卡提成" :visible.sync="dialogFormVisible">
      <el-form :model="dialogForm"  label-width="100px" size="mini">
        <el-form-item label="是否提成">
          <el-radio-group v-model="dialogForm.isCommission">
            <el-radio label="1" >是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择提成方式" v-if="dialogForm.isCommission ==1">
          <el-select v-model="dialogForm.commissionType">
            <el-option label="比例提成" value="0"></el-option>
            <el-option label="固定提成" value="1"></el-option>
          </el-select>
          <el-input v-model="dialogForm.number"></el-input>
          <span v-if="dialogForm.commissionType == 0">%</span>
          <span v-else>元</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="samll">取 消</el-button>
        <el-button type="primary" @click="onConfirmSet" size="samll">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import u from "@/util/state";
import {
  getShopList,
  saveServiceOrShop,
  getServiceShopListPage,
  deleteServiceOrShop,
  timesCardListPage,
  removeTimesCard,
  insertListSubCardDeduct
} from "@/api";
import util from "@/util";
export default {
  computed: mapState(["merchantId", "sub", "power", "soUrce","isShop"]),
  data() {
    return {
      states: u.states,
      checkedCities1: [],
      // 多选-----------------
      multipleSelections: [],
      // 分配门店----------------
      dialogVisible_store: false,
      store_fenpei: [],
      pageSize_s: 3,
      pageNum_s: 1,
      keyword_s: "",
      pageTotal_s: "",
      multipleSelection_store_s: [],
      // 查看分配门店----------------
      dialogVisible_check_store: false,
      keyword_store: "",
      handleViewStore_id: "",
      tableDataStore: [],
      multipleSelection_store: [],
      cities: [
        { name: "shanghai", id: "1" },
        { name: "shang", id: "2" },
        { name: "bei", id: "3" }
      ],
      // 搜索框
      selectdata: {
        keyword: "",
        status: null,
        isCommission: '',
        frequency: ''
      },
      // 表格
      tableData: [],
      // 分页开始
      total: 0,
      pageSize: 20,
      totalItems: 0,
      currentPage: 1,
      options: [
        {
          label: "全部",
          value: null
        },
        {
          label: "上架",
          value: 0
        },
        {
          label: "下架",
          value: 1
        }
      ],
      commissionOption: [
          {
          label: "全部",
          value: ''
        },
        {
          label: "否",
          value: 0
        },
        {
          label: "是",
          value: 1
        }
      ],
      dialogFormVisible: false,
      dialogForm: {
        isCommission: '1',
        commissionType: '1',
        number: ''
      }
    };
  },
  mounted() {
    this.cikalist(20, 1);
  },
  watch: {
    sub: {
      handler: function(val, oldVal) {
        if (oldVal != null && val == false) {
          this.cikalist(20, 1);
        }
      },
      deep: true
    }
  },
  methods: {
    //配置权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelections = val;
    },
    //分配门店
    assignStore() {
      if (this.multipleSelections.length > 0) {
        this.getShopList(this.pageSize_s, 1);
        this.dialogVisible_store = true;
      } else {
        this.$message({
          showClose: true,
          message: "请先选择次卡！",
          type: "error"
        });
      }
    },
    getShopList(pageSize, pageNum) {
      let data = {
        companyId: this.merchantId,
        pageSize: pageSize,
        pageNum: pageNum,
        keyword: this.keyword_s,
        flag: "1"
      };
      getShopList(data).then(res => {
        this.store_fenpei = res.data.list;
      });
    },
    handleFenpei_do_search() {
      this.getShopList(this.pageSize_s, this.pageNum_s);
    },
    // 分配门店多选方法
    changeFun_addStore(val) {
      this.multipleSelection_store_s = val;
    },
    // 搜索分配门店
    handleFenpei_search() {
      let keyword = this.keyword_store;
      this.getActivityShop();
    },
    // 点击立即分配
    handleFenpei_s() {
      if (this.multipleSelection_store_s.length > 0) {
        saveServiceOrShop({
          serviceId: JSON.stringify(this.multipleSelections),
          shopId: JSON.stringify(this.multipleSelection_store_s)
        }).then(res => {
          this.$message({
            type: "success",
            message: "分配成功!"
          });
          this.dialogVisible_store = false;
          this.cikalist(20, 1);
        });
      } else {
        this.$message({
          type: "error",
          message: "请先选择门店!"
        });
      }
    },
    // 多个取消分配
    change_store(val) {
      this.multipleSelection_store = val;
    },
    // 点击查看分配门店
    handleViewStore(id) {
      this.handleViewStore_id = id;
      this.getActivityShop();
      this.dialogVisible_check_store = true;
    },
    // 根据折扣id获取分配的门店
    getActivityShop() {
      let data = {
        serviceId: this.handleViewStore_id,
        keyword: this.keyword_store,
        pageSize: 20,
        pageNum: 1,
        flag: "1"
      };
      getServiceShopListPage(data).then(res => {
        this.tableDataStore = res.data.list;
      });
    },
    // 多个取消分配方法
    handleCancelFenpei_more(id) {
      let service_id = this.handleViewStore_id;
      let Data = new FormData();
      Data.append("serviceId", service_id);
      Data.append("shopId", id);
      deleteServiceOrShop(Data).then(res => {
        this.getActivityShop();
      });
    },

    // 新增次卡
    routerPush(name, param) {
      if (this.soUrce == "5") {
        util.routerTo(
          "/operate-management/serve-management/subcard-list/subcard-add",
          {
            showTab: "1"
          }
        );
      } else {
        util.routerTo(
          "/operate-management/serve-management/subcard-list/subcard-add"
        );
      }
    },
    // 编辑
    routerPushdetail(showTab, cardId = "") {
      if (this.soUrce == "5") {
        util.routerTo(
          "/operate-management/serve-management/subcard-list/subcard-edit",
          {
            showTab: "3",
            cardId: cardId
          }
        );
      } else {
        util.routerTo(
          "/operate-management/serve-management/subcard-list/subcard-edit",
          {
            showTab: "1",
            cardId: cardId
          }
        );
      }
    },
    // 查看
    routerPushdetails(showTab, cardId = "") {
      if (this.soUrce == "5") {
        util.routerTo(
          "/operate-management/serve-management/subcard-list/subcard-edit",
          {
            showTab: "2",
            cardId: cardId
          }
        );
      } else {
        util.routerTo(
          "/operate-management/serve-management/subcard-list/subcard-edit",
          {
            showTab: "2",
            cardId: cardId
          }
        );
      }
    },
    // 销售数量
    routerPushNumber(cardId = "") {
      util.routerTo(
        "/operate-management/serve-management/subcard-list/subcard-number",
        {
          cardId: cardId
        }
      );
    },
    // 分页次卡列表
    cikalist(pageSize, pageNum) {
      let data = {
        pageNum: pageNum,
        pageSize: pageSize,
        companyId: this.merchantId,
        name: this.selectdata.keyword,
        status: this.selectdata.status,
        royalty: this.selectdata.isCommission,
        times: this.selectdata.frequency
      };
      timesCardListPage(data).then(res => {
        this.tableData = res.data.list;
        this.totalItems = res.data.totalRecord;
      });
    },
    // 转时间戳
    timestamps: function(row, column) {
      return (
        util.foryear(parseInt(row.createTime)) +
        " " +
        util.fortime(parseInt(row.createTime))
      );
    },
    searchSelect() {
      this.selectdatas = this.selectdata;
      this.cikalist(this.pageSize, this.currentPage);
    },
    deletes(id) {
      this.$confirm("确定要删除吗?", "提示", {
        center: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      }).then(() => {
        let data = {
          id: id
        };
        removeTimesCard(data).then(res => {
          if (res.code == "200") {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "success"
            });
            this.cikalist(20, 1);
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error"
            });
          }
        });
      });
    },
    //跳页
    toPage() {
      this.cikalist(this.pageSize, this.currentPage);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.cikalist(this.pageSize, 1);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.cikalist(this.pageSize, this.currentPage);
    },
    onSetCommission() {
      if(this.multipleSelections.length==0) {
        this.$message.error("请选择要设置的次卡")
      }else {
        this.dialogFormVisible = true
      }
    },
    onConfirmSet() {
      let ids = [],data = {}
      if (this.dialogForm.isCommission == '1' && (!this.dialogForm.number || this.dialogForm.number == 0)) {
         this.$message.error('请输入提成值且大于0！')
         return
      }

      for (let i = 0; i < this.multipleSelections.length; i++) {
        const element = this.multipleSelections[i];
        ids.push(element.id)
      }
      data = {
        ids: ids.join(','),
        deductAmount: this.dialogForm.number,
        royalty: this.dialogForm.isCommission,
        deductType: this.dialogForm.commissionType
      }
      insertListSubCardDeduct(data).then(res => {
        if(res.code == 200) {
          this.dialogFormVisible = false;
           this.cikalist(this.pageSize, this.currentPage);
        }
      })
      console.log(this.dialogForm)
    }
  }
};
</script>
<style scoped>
.inp-sr {
  width: 300px;
}
   .el-dialog .el-input {
     width: 100px;
   }
</style>
